package util.parsing;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

import scene.shape.geometry.Triangle;
import util.TexCoord2f;
import util.Vector3f;


public class ObjParser {

	public static List<Triangle> parseObjFile(String filename){
		List<Vector3f> vertices = new ArrayList<Vector3f>();
		List<Triangle> triangles = Collections.synchronizedList(new ArrayList<Triangle>());
		List<Vector3f> normals = new ArrayList<Vector3f>();
		List<TexCoord2f> texcoords = new ArrayList<TexCoord2f>();
		Scanner scan = null;
		try {
			scan = new Scanner(new File(filename));
		} catch (FileNotFoundException e) {
			System.out.println("File not found: " + filename);
			e.printStackTrace();
			return null;
		}
		while(scan.hasNextLine()){
			String line = scan.nextLine();
			if(line.matches("^v .*$")){
				line = line.substring(2);
				try {
					vertices.add(ParserUtils.parseVector3f(line));
				} catch (ParseException e) {
					System.out.println("Error parsing vector3f: " + line);
					e.printStackTrace();
				}
			}
			else if(line.matches("^vn .*")){
				line = line.substring(2);
				try {
					normals.add(ParserUtils.parseVector3f(line));
				} catch (ParseException e) {
					System.out.println("Error parsing vector3f: " + line);
					e.printStackTrace();
				}
			}
			else if(line.matches("^vt .*")){
				line = line.substring(2);
				try {
					texcoords.add(ParserUtils.parseTexCoord2f(line));
				} catch (ParseException e) {
					System.out.println("Error parsing tuple2f: " + line);
					e.printStackTrace();
				}
			}
			else if(line.matches("^f .*")){
				line = line.substring(2);
				String[] triplets = line.split("\\s");
				Vector3f[] triangleVertices = new Vector3f[3];
				Vector3f[] normalVertices = new Vector3f[3];
				TexCoord2f[] texVertices = new TexCoord2f[3];
				for(int i = 0; i < 3; i++){
					String[] numbersString = triplets[i].split("/");
					triangleVertices[i] = vertices.get(Integer.parseInt(numbersString[0])-1);
					if(!numbersString[1].equals(""))
						texVertices[i] = texcoords.get(Integer.parseInt(numbersString[1])-1);
					normalVertices[i] = normals.get(Integer.parseInt(numbersString[2])-1);
				}
				triangles.add(new Triangle(triangleVertices[0], triangleVertices[1], triangleVertices[2],
						normalVertices[0], normalVertices[1], normalVertices[2],
						texVertices[0], texVertices[1], texVertices[2]));
			}
		}
		return triangles;
	}

}
